import { useMemo } from 'react';
import { usePlatformStore } from '../../stores/platform';
import { 
  PLATFORM_MENU_CONFIG, 
  USER_MENU_CONFIG, 
  filterMenuByPermissions
} from '../../constants/platformMenu';
import { PlatformPermissions, PlatformRoles } from '../../constants/platformPermissions';
import { renderIcon } from '../../utils/iconUtils';

/**
 * 简化的权限检查函数
 */
function hasPermission(userPermission: string, requiredPermission: string): boolean {
  if (!userPermission || !requiredPermission) {
    return false;
  }

  // 超级权限
  if (userPermission === 'platform:*') {
    return true;
  }

  // 精确匹配
  if (userPermission === requiredPermission) {
    return true;
  }

  // 通配符匹配 (如 platform:tenant:* 包含 platform:tenant:read)
  if (userPermission.endsWith(':*')) {
    const prefix = userPermission.substring(0, userPermission.length - 1);
    return requiredPermission.startsWith(prefix);
  }

  return false;
}

/**
 * 统一的平台权限管理Hook
 * 合并了菜单管理和权限检查功能
 */
export const usePlatformPermission = () => {
  const { user, permissions } = usePlatformStore();

  // 获取用户角色列表
  const userRoles = useMemo(() => {
    if (!user?.roleIds) return [];
    return user.roleIds.split(',').map(role => role.trim());
  }, [user?.roleIds]);

  // 是否为超级管理员
  const isSuperAdmin = user?.isSuperAdmin || false;

  // 过滤有权限的主菜单项
  const mainMenuItems = useMemo(() => {
    const filteredMenu = filterMenuByPermissions(
      PLATFORM_MENU_CONFIG,
      permissions,
      userRoles,
      isSuperAdmin
    );

    // 转换为Antd菜单格式
    return filteredMenu.map(item => ({
      key: item.path,
      icon: renderIcon(item.icon),
      label: item.label,
    }));
  }, [permissions, userRoles, isSuperAdmin]);

  // 过滤有权限的用户菜单项
  const userMenuItems = useMemo(() => {
    const filteredUserMenu = filterMenuByPermissions(
      USER_MENU_CONFIG,
      permissions,
      userRoles,
      isSuperAdmin
    );

    return filteredUserMenu.map(item => ({
      key: item.key,
      icon: renderIcon(item.icon),
      label: item.label,
      path: item.path,
    }));
  }, [permissions, userRoles, isSuperAdmin]);

  // 权限检查方法
  const checkPermission = (permission: string): boolean => {
    if (isSuperAdmin) return true;
    return permissions.some(userPerm => hasPermission(userPerm, permission));
  };

  const checkAnyPermission = (permissionsToCheck: string[]): boolean => {
    if (isSuperAdmin) return true;
    return permissionsToCheck.some(required =>
      permissions.some(userPerm => hasPermission(userPerm, required))
    );
  };

  const checkAllPermissions = (permissionsToCheck: string[]): boolean => {
    if (isSuperAdmin) return true;
    return permissionsToCheck.every(required =>
      permissions.some(userPerm => hasPermission(userPerm, required))
    );
  };

  // 角色检查方法
  const checkRole = (roleCode: string): boolean => {
    if (isSuperAdmin) return true;
    return userRoles.includes(roleCode);
  };

  const checkAnyRole = (roleCodes: string[]): boolean => {
    if (isSuperAdmin) return true;
    return roleCodes.some(role => userRoles.includes(role));
  };

  // 菜单权限检查
  const hasMenuPermission = (menuKey: string): boolean => {
    const allMenuItems = [...PLATFORM_MENU_CONFIG, ...USER_MENU_CONFIG];
    const menuItem = allMenuItems.find(item => item.key === menuKey);
    
    if (!menuItem) return false;
    
    return filterMenuByPermissions(
      [menuItem],
      permissions,
      userRoles,
      isSuperAdmin
    ).length > 0;
  };

  // 租户访问检查
  const canAccessTenant = (tenantId: string): boolean => {
    if (!user) return false;
    
    // 超级管理员可以访问所有租户
    if (isSuperAdmin) return true;

    // 检查租户访问类型
    if (user.tenantAccessType === 'all') return true;
    if (user.tenantAccessType === 'none') return false;
    
    if (user.tenantAccessType === 'specific' && user.accessibleTenantIds) {
      const accessibleIds = user.accessibleTenantIds.split(',').map((id: string) => id.trim());
      return accessibleIds.includes(tenantId);
    }

    // 兼容性检查：使用accessibleTenants数组
    if (user.accessibleTenants) {
      return user.accessibleTenants.includes(tenantId);
    }

    return false;
  };

  return {
    // 用户信息
    user,
    userRoles,
    isSuperAdmin,
    
    // 菜单项
    mainMenuItems,
    userMenuItems,
    
    // 权限检查
    checkPermission,
    checkAnyPermission,
    checkAllPermissions,
    hasPermission: checkPermission, // 别名，保持兼容性
    
    // 角色检查
    checkRole,
    checkAnyRole,
    hasRole: checkRole, // 别名，保持兼容性
    
    // 菜单权限检查
    hasMenuPermission,
    
    // 租户访问检查
    canAccessTenant,
    
    // 便捷方法
    canManageTenants: checkAnyPermission([PlatformPermissions.TENANT_ALL, PlatformPermissions.TENANT_READ]),
    canViewTenants: checkAnyPermission([PlatformPermissions.TENANT_ALL, PlatformPermissions.TENANT_READ]),
    canManageUsers: checkAnyPermission([PlatformPermissions.PLATFORM_USER_ALL, PlatformPermissions.PLATFORM_USER_READ]),
    canViewUsers: checkAnyPermission([PlatformPermissions.PLATFORM_USER_ALL, PlatformPermissions.PLATFORM_USER_READ]),
    canManageSystem: checkAnyPermission([PlatformPermissions.SYSTEM_ALL, PlatformPermissions.SYSTEM_CONFIG])
  };
};

// 重新导出权限常量，保持向后兼容
export { PlatformPermissions, PlatformRoles };
